package com.yisu.auction.manager.website.controller.memberInfo;

import com.yisu.auction.ewf.common.web.EasyUIGrid;
import com.yisu.auction.ewf.entity.Member;
import com.yisu.auction.manager.core.service.IMemberService;
import com.yisu.auction.manager.domain.request.memberPackage.MemberRequest;
import com.yisu.auction.manager.domain.vo.baseInfoPackageVos.MemberVo;
import com.yisu.auction.manager.website.controller.BaseController;
import com.yisu.auction.manager.website.factoryClassPackage.excelFactory.DateTypeEnum;
import com.yisu.auction.manager.website.factoryClassPackage.excelFactory.IExcelFactoryService;
import com.yisu.auction.manager.website.factoryClassPackage.excelFactory.IExportService;
import com.yisu.auction.manager.website.factoryClassPackage.excelFactory.impl.ExcelFactoryServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * author: 赵杰
 * Business Description：会员基本信息
 * createTime：2017/8/21
 */
@RequestMapping(value = "/member")
@Controller
public class MemberController extends BaseController {
    @Resource
    private IMemberService iMemberService;


    // 报表临时文件目录
    public static final String BI_TMP_FILES = MemberController.class.getResource("/").getPath() + "biTempFiles/";

    /**
     * author: 赵杰
     * Business Description：获取会员基本信息
     *
     * @param model
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/index.htm")
    public String index(Model model, HttpServletRequest request, MemberRequest memberRequest) throws Exception {
        try {
            if (memberRequest.getKeyword() != null) {
                memberRequest.setKeyword(URLDecoder.decode(memberRequest.getKeyword(), "utf-8"));
            }
            if (StringUtils.isEmpty(memberRequest.getSortDesc())) {
                memberRequest.setSortDesc("CONSUMPTION_AMOUNT");
            }
            if (memberRequest.getStartTime() != null && memberRequest.getEndTime() != null) {
                memberRequest.setStartTime(URLDecoder.decode(memberRequest.getStartTime(), "utf-8"));
                memberRequest.setEndTime(URLDecoder.decode(memberRequest.getEndTime(), "utf-8"));
            }
            EasyUIGrid<MemberVo> memberEasyUIGrid = iMemberService.getMemberInfoByPage(memberRequest);
            model.addAttribute("MemberVos", memberEasyUIGrid.getRows());
            model.addAttribute("currentPage", memberRequest.getPage());
            model.addAttribute("totalPages", (memberRequest.getTotalRecords() / memberRequest.getRows()) + 1);
            model.addAttribute("keyword", memberRequest.getKeyword());
            model.addAttribute("startTime", memberRequest.getStartTime());
            model.addAttribute("sortDesc", memberRequest.getSortDesc());
            model.addAttribute("sortRule", memberRequest.getSortRule());
            model.addAttribute("endTime", memberRequest.getEndTime());
        } catch (Exception e) {
            logger.error("获取会员基本信息异常：" + e.getMessage());
        }
        return "/memberInfo/baseInfo/index";
    }

    /**
     * 导出数据分析报表
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/exportUserReportAction.htm")
    public String exportUserReportAction(Model model, HttpServletResponse response, MemberRequest memberRequest) throws IOException {
        SimpleDateFormat sformat = new SimpleDateFormat("yyyyMMddHHmm");
        String fileName = "用户报表" + sformat.format(new Date()) + ".xls";
        File file = new File(BI_TMP_FILES);
        if (!file.exists())
            file.mkdir();
        String fileFullPath = BI_TMP_FILES + fileName;
        List<MemberVo> memberVos = iMemberService.getAllMemberInfos(memberRequest);
        if (!CollectionUtils.isEmpty(memberVos)) {
            IExcelFactoryService iExcelFactoryService = new ExcelFactoryServiceImpl();
            IExportService iExportService = iExcelFactoryService.factory(DateTypeEnum.MEMBER_DATE);
            iExportService.export(fileFullPath, memberVos);
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment;filename=\""
                    + new String(fileName.getBytes(), "ISO8859-1") + "\"");
            byte[] buffer = File2byte(fileFullPath);
            response.setContentLength(buffer.length);
            response.getOutputStream().write(buffer);
            response.getOutputStream().flush();
            response.getOutputStream().close();
        }
        return null;
    }


    public static byte[] File2byte(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

}
